package com.dilean.impl.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import com.dilean.api.model.Conversation;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.hibernate.annotations.IndexColumn;

import com.dilean.api.model.Message;
import com.dilean.api.model.Person;

@Entity
@Table(name = "CONVERSATIONS")
public class ConversationImpl extends AbstractEntityImpl implements Conversation 
{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DILEAN_ID_SEQ")
    @SequenceGenerator(name = "DILEAN_ID_SEQ", sequenceName = "DILEAN_ID_SEQ", allocationSize = 1)
    @Column(name = "ID")
    private Integer id;

    @Column(name = "NAME", unique = false, nullable = false)
    private String name;

    @Override
    public Integer getId()
    {
        return id;
    }

    @Override
    public String getName()
    {
        return name;
    }

    @Override
    public void setId(Integer id)
    {
        this.id = id;
    }

    @Override
    public void setName(String name)
    {
        this.name = name;
    }
    
	public ConversationImpl() {
		
	}
    
    @ManyToMany(targetEntity = PersonImpl.class)
    @JoinTable(name="PERS_CONVERSATIONS",
    		joinColumns=@JoinColumn(name="CONVERSATION_ID"),
    		inverseJoinColumns=@JoinColumn(name="PERSON_ID"))
    private Collection<Person> persons = new HashSet<Person>();
    
	@OneToMany(targetEntity = MessageImpl.class, cascade={CascadeType.ALL}, mappedBy="conversation")
    @IndexColumn(name = "ORDER_NUMBER")
    private List<Message> messages = new ArrayList<Message>();
    
	@Override
	public Collection<Person> getPersons() {
		return persons;
	}
	
	@Override
	public void setPersons(Collection<Person> persons) {
		this.persons = persons;
	} 

	@Override
	public List<Message> getMessages() {
		return this.messages;
	}
	
	@Override
	public void setMessages(List<Message> messages) {
		this.messages = messages;
	} 
	
	@Override
	public void addPerson(Person person) {
		persons.add(person);
	}
	
}
